package com.lixinlei.security.auth.oauth2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 就是要配置 AuthenticationManager，让 AuthenticationManager 告诉认证服务器合法的用户有谁
 */
@Configuration
@EnableWebSecurity // 让安全配置生效
public class OAuth2WebSecurityConfig extends WebSecurityConfigurerAdapter {

    // 获取合法的用户信息的，需要自己实现一下这个接口，根据用户名获取用户信息
    @Autowired
    private UserDetailsService userDetailsService;

    // Spring Security 封装的加密工具
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 构建 AuthenticationManager
     * 通过 userDetailsService 获取用户信息，
     * 通过 passwordEncoder() 把获取到的用户密码，和用户输入的密码比对
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());
    }

    /**
     * 把上面配置的 AuthenticationManager 暴露成一个 Bean
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}
